<template>
	<xn-form-container
		title="授权用户"
		:width="drawerWidth"
		:visible="visible"
		:destroy-on-close="true"
		:show-pagination="false"
		@close="onClose"
	>
		<a-spin :spinning="spinningLoading">
			<a-select
				v-model:value="checkedList"
				mode="multiple"
				style="width: 100%"
				placeholder="选择用户"
				show-search
				option-filter-prop="label"
				:options="userOptions"
			></a-select>
		</a-spin>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" :loading="submitLoading" @click="onSubmit">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="grantResourceForm">
	import api from './api'
	import menuApi from '../menu/api'
	const spinningLoading = ref(false)
	const firstShowMap = ref({})
	const emit = defineEmits({ successful: null })
	const submitLoading = ref(false)
	// 抽屉的宽度
	const drawerWidth = 500
	// 自动获取宽度，默认获取浏览器的宽度的90%
	//(window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) * 0.9

	const echoDatalist = ref([])
	const moduleId = ref('')

	const userOptions = ref([])
	const checkedList = ref([])

	// 获取数据
	const loadData = async () => {
		// 获取表格数据
		spinningLoading.value = true
		const res = await api.findUserList({ pagesize: 9999, pageNow: 1 })
		userOptions.value = res.record.map((item) => {
			return {
				value: item.id,
				label: item.username
			}
		})
		const list = await api.findUserByRoleId({ pagesize: 9999, pageNow: 1, role_id: resultDataModel.id })
		checkedList.value = list.record.map((item) => item.id)
		spinningLoading.value = false
	}
	const visible = ref(false)
	// 返回的数据模型，最终需要转换成这样
	let resultDataModel = {
		id: '',
		grantInfoList: []
	}
	// 打开抽屉
	const onOpen = (record) => {
		resultDataModel.id = record.id
		visible.value = true
		firstShowMap.value = {}
		loadData()
	}
	// 遍历字段

	// 关闭抽屉
	const onClose = () => {
		// 将这些缓存的给清空
		checkedList.value = []
		resultDataModel.id = ''
		visible.value = false
	}
	// 验证并提交数据
	const onSubmit = () => {
		const param = checkedList.value.map((item) => ({
			role_id: resultDataModel.id,
			user_id: item
		}))
		submitLoading.value = true
		api
			.updateRoleUser(param)
			.then(() => {
				onClose()
				emit('successful')
				refreshCacheMenu()
			})
			.finally(() => {
				submitLoading.value = false
			})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>

<style scoped>
	/* 重写复选框的样式 */
	.ant-checkbox-wrapper {
		margin-left: 0px !important;
		padding-top: 2px !important;
		padding-bottom: 2px !important;
	}
</style>
